AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( "shared.lua" )

local AMMO_CRATE_CLOSE_DELAY = 1.5

function ENT:Initialize()
	
	self:SetModel("models/items/ammocrate_smg1.mdl")
	
	self:PhysicsInit(SOLID_VPHYSICS)
	self:SetMoveType(MOVETYPE_NONE)
	self:SetSolid(SOLID_VPHYSICS)
	self:SetUseType(SIMPLE_USE)
	self:DrawShadow(false)
	
	local phys = self:GetPhysicsObject()
	if (phys:IsValid()) then
	
		phys:SetMass( 100 )
		phys:Wake()
		phys:EnableGravity( false )
		phys:EnableMotion( false )
	end
	
	self:ResetSequence( self:LookupSequence("Idle") )
	self:SetBodygroup( 1,  true )
	
	self.CloseTime = CurTime()
	self.AnimTime = CurTime()
	
	self:SetCycle( 0 )
end

function ENT:CheckTeam( team )
	local skin = self:GetSkin()
	
	if skin == 1 then
		return true
	end
	if skin == 2 then
		return team == Team.BLUE
	end
	if skin == 3 then
		return team == Team.RED
	end
	
end

function ENT:Use( ply )
	
	if Game.State() != Game.FIGHT or !ValidPlayer( ply ) or not self:CheckTeam( ply:Team() ) then
		return
	end
	
	//Let players not spawn the ammo create
	if self.Think == self.CrateThink then
		return
	end
	
	ply:RemoveAllAmmo()
	ply:Class():SetAmmo()
	
	local Sequence = self:LookupSequence( "Close" )
	
	if self:GetSequence() != Sequence then
		// Animate!
		self:ResetSequence( Sequence )

		// Make sound
		self:EmitSound("AmmoCrate.Open", 100, 100 )
		
		self.Think = self.CrateThink
	end

	// Don't close again for two seconds
	self.CloseTime = CurTime() + AMMO_CRATE_CLOSE_DELAY

end

function ENT:CrateThink()
	
	self:NextThink( CurTime() + 0.1 )

	local CloseSeq = self:LookupSequence( "Idle" )
	
	// Start closing if we're not already
	if self:GetSequence() != CloseSeq then
		// Not ready to close?
		if self.CloseTime <= CurTime() then
			self:ResetSequence( CloseSeq )
			
			local Duration = self:SequenceDuration()
			self.AnimTime = CurTime() + Duration
			
		end
		
	else
		// See if we're fully closed
		if CurTime() >= self.AnimTime then
			// Stop thinking
			self.Think = nil
			self:EmitSound("AmmoCrate.Close", 100, 100 )
			
			self:ResetSequence( self:LookupSequence( "Idle" ) )
			self:SetBodygroup( 1, true )
		end
		
	end
end